package demo;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 函数式编程实现if else
 *
 * @author dingwen
 * 2021.06.04 09:33
 */
public class OptionalConsumer<T> implements Consumer<Optional<T>> {

    private final Consumer<T> ifAction;
    private final Runnable elseAction;
    private Predicate<Optional<T>> condition = Optional::isPresent;

    public OptionalConsumer(Consumer<T> ifAction, Runnable elseAction) {
        super();
        this.ifAction = ifAction;
        this.elseAction = elseAction;
    }

    public OptionalConsumer(Consumer<T> ifAction, Runnable elseAction, Predicate<Optional<T>> condition) {
        super();
        this.ifAction = ifAction;
        this.elseAction = elseAction;
        this.condition = condition;
    }

    public static <T> OptionalConsumer<T> of(Consumer<T> ifAction, Runnable elseAction) {
        return new OptionalConsumer<T>(ifAction, elseAction);
    }

    public static <T> OptionalConsumer<T> of(Consumer<T> ifAction, Runnable elseAction, Predicate<Optional<T>> condition) {
        return new OptionalConsumer<T>(ifAction, elseAction, condition);
    }

    @Override
    public void accept(Optional<T> t) {
        if (condition.test(t)) {
            t.ifPresent(ifAction);
        } else {
            elseAction.run();
        }
    }

    @Override
    public Consumer<Optional<T>> andThen(Consumer<? super Optional<T>> after) {
        Objects.requireNonNull(after);
        return (Optional<T> t) -> {
            accept(t);
            after.accept(t);
        };
    }
}
